package cn.may.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author mayuanbao
 * @date 2019-06-04 13:04
 */
@Aspect
@Component
@Slf4j
public class HttpAspect {
//    private static final Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    @Pointcut("execution(public * cn.may.controller.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            //url
            log.info("url={}", request.getRequestURL());
            //request method
            log.info("method={}", request.getMethod());
            //ip
            log.info("ip={}", request.getRemoteAddr());
            //host
            log.info("host={}", request.getRemoteHost());
            //class method
            log.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            //param
            log.info("args={}", joinPoint.getArgs());
        } else {
            log.info("ServletRequestAttributes is null");
        }
    }

    @After("log()")
    public void doAfter() {
        log.info("后处理...");
    }

    @AfterReturning(returning = "object", pointcut = "log()")
    private void doAfterReturning(Object object) {
        log.info("response={}", object);
    }
}
